package com.witmore.neutron.ai.mcp.server.trading.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.witmore.neutron.ai.mcp.server.trading.dto.StockRealTimeInfoResponse;
import com.witmore.neutron.ai.mcp.server.trading.dto.StockRealTimeInfoSingleResponse;
import com.witmore.neutron.ai.mcp.server.trading.dto.StockUpDownResponse;
import com.witmore.neutron.ai.mcp.server.trading.service.AkshareService;
import com.witmore.neutron.ai.mcp.server.trading.service.IAkShareMcpService;
import com.witmore.neutron.ai.mcp.server.trading.dto.StockRealTimeInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: IAkShareMcpServiceImpl
 * Author: 豆子高
 * Date: 2025/8/8 13:56
 */
@Slf4j
@Service
public class AkShareMcpServiceImpl implements IAkShareMcpService {

    @Autowired
    private AkshareService akshareService;

    @Autowired
    private RedisTemplate<String, Map<Long, Double>> redisTemplate;

    @Override
    public StockRealTimeInfoSingleResponse stockIndividualInfoEm(String symbol) throws IOException {
        log.info("股票信息查询 stockIndividualInfoEm: {}", symbol);
        String stockIndividualInfoEm = akshareService.stockIndividualInfoEm(symbol);
        List<StockRealTimeInfo> stockRealTimeInfos = JSONArray.parseArray(stockIndividualInfoEm, StockRealTimeInfo.class);
        // 最新数据缓存在库内（增加Redis连接异常处理）
        try {
            Map<Long, Double> timestampMap = new HashMap<>();
            timestampMap.put(System.currentTimeMillis(), getCurrentPrice(stockRealTimeInfos));
            redisTemplate.opsForList().leftPush(symbol, timestampMap);
            log.debug("成功将股票信息存入Redis缓存，key: {}", symbol);
        } catch (Exception redisException) {
            log.warn("Redis存储失败，但不影响查询结果: {}", redisException.getMessage());
            // 继续执行，不影响返回结果
        }
        return new StockRealTimeInfoSingleResponse("200", "成功", stockRealTimeInfos, System.currentTimeMillis());
    }

    @Override
    public StockUpDownResponse stockChangesUpDown(String symbol) {
        return null;
    }


    /**
     * 批量获取指定股票代码的实时行情数据
     *
     * @param symbols 股票代码列表，用逗号分隔，例如："000001,000002,600036"
     * @return 匹配的股票实时行情数据列表
     * @throws IOException 网络请求异常
     */
    @Override
    public List<StockRealTimeInfoResponse> stockRealTimeInfoEm(String symbols) throws IOException {
        log.info("批量股票实时行情查询 stockRealTimeInfoEm: {}", symbols);

        // 调用第三方接口获取所有股票数据（东财实时行情）
        String allStockData = akshareService.stockRealTimeInfoEm();
        List<StockRealTimeInfoResponse> allStocks = JSONArray.parseArray(allStockData, StockRealTimeInfoResponse.class);

        if (allStocks == null || allStocks.isEmpty()) {
            log.warn("从第三方接口获取股票数据为空");
            return new java.util.ArrayList<>();
        }

        log.info("从第三方接口获取到 {} 条股票数据", allStocks.size());

        // 解析传入的股票代码列表（支持逗号分隔）
        String[] symbolArray = symbols.trim().split(",");
        List<String> targetSymbols = Arrays.asList(symbolArray);

        // 去除空格并转换为大写，便于匹配
        targetSymbols = targetSymbols.stream()
                .map(String::trim)
                .map(String::toUpperCase)
                .collect(java.util.stream.Collectors.toList());

        log.info("待查询的股票代码: {}", targetSymbols);

        // 筛选出指定股票代码的数据
        List<String> finalTargetSymbols = targetSymbols;
        List<StockRealTimeInfoResponse> result = allStocks.stream()
                .filter(stock -> stock.getCode() != null &&
                        finalTargetSymbols.contains(stock.getCode().trim().toUpperCase()))
                .collect(java.util.stream.Collectors.toList());

        log.info("成功筛选出 {} 条匹配的股票数据", result.size());
        return result;
    }


    /**
     * 从股票实时信息中提取当前价格
     */
    private double getCurrentPrice(List<StockRealTimeInfo> stockInfos) {
        if (stockInfos == null || stockInfos.isEmpty()) {
            return 0;
        }

        for (StockRealTimeInfo info : stockInfos) {
            if ("最新".equals(info.item())) {
                try {
                    return Double.parseDouble(info.value());
                } catch (NumberFormatException e) {
                    log.warn("解析股票价格失败: {}", info.value());
                }
            }
        }
        return 0;
    }

}
